{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "# Introduction to Keras for Engineers\n",
    "\n",
    "**Author:** [fchollet](https://twitter.com/fchollet)<br>\n",
    "**Date created:** 2020/04/01<br>\n",
    "**Last modified:** 2020/04/28<br>\n",
    "**Description:** Everything you need to know to use Keras to build real-world machine learning solutions."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Setup\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "from tensorflow import keras\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Introduction\n",
    "\n",
    "Are you a machine learning engineer looking to use Keras\n",
    "to ship deep-learning powered features in real products? This guide will serve\n",
    "as your first introduction to core Keras API concepts.\n",
    "\n",
    "In this guide, you will learn about:\n",
    "\n",
    "- How to prepare you data before training a model (by turning it into either NumPy\n",
    " arrays or `tf.data.Dataset` objects).\n",
    "- How to do data preprocessing, for instance feature normalization or vocabulary\n",
    " indexing.\n",
    "- How to build a model that turns your data into useful predictions,\n",
    "using the Keras Functional API.\n",
    "- How to train your model with the built-in Keras `fit()` method, while being\n",
    "mindful of checkpointing, metrics monitoring, and fault tolerance.\n",
    "- How to evaluate your model on a test data and how to use it for inference on new data.\n",
    "- How to customize what `fit()` does, for instance to build a GAN.\n",
    "- How to speed up training by leveraging multiple GPUs.\n",
    "- How to refine your model through hyperparameter tuning.\n",
    "\n",
    "At the end of this guide, you will get pointers to end-to-end examples to solidify\n",
    " these concepts:\n",
    "\n",
    "- Image classification\n",
    "- Text classification\n",
    "- Credit card fraud detection\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Data loading & preprocessing\n",
    "\n",
    "Neural networks don't process raw data, like text files, encoded JPEG image files, or\n",
    " CSV files. They process **vectorized** & **standardized** representations.\n",
    "\n",
    "- Text files needs to be read into string tensors, then split into words. Finally, the\n",
    " words need to be indexed & turned into integer tensors.\n",
    "- Images need to be read and decoded into integer tensors, then converted to floating\n",
    " point and normalized to small values (usually between 0 and 1).\n",
    "- CSV data needs to be parsed, with numerical features converted to floating point\n",
    " tensors and categorical features indexed and converted to integer tensors.\n",
    "Then each feature typically needs to be normalized to zero-mean and unit-variance.\n",
    "- Etc.\n",
    "\n",
    "Let's start with data loading.\n",
    "\n",
    "## Data loading\n",
    "\n",
    "Keras models accept three types of inputs:\n",
    "\n",
    "- **NumPy arrays**, just like Scikit-Learn and many other Python-based libraries. This\n",
    " is a good option if your data fits in memory.\n",
    "- **[TensorFlow `Dataset` objects](https://www.tensorflow.org/guide/data)**. This is a\n",
    "high-performance option that is more suitable for datasets that do not fit in memory\n",
    " and that are streamed from disk or from a distributed filesystem.\n",
    "- **Python generators** that yield batches of data (such as custom subclasses of\n",
    "the `keras.utils.Sequence` class).\n",
    "\n",
    "Before you start training a model, you will need to make your data available as one of\n",
    "these formats. If you have a large dataset and you are training on GPU(s), consider\n",
    "using `Dataset` objects, since they will take care of performance-critical details,\n",
    " such as:\n",
    "\n",
    "- Asynchronously preprocessing your data on CPU while your GPU is busy, and bufferring\n",
    " it into a queue.\n",
    "- Prefetching data on GPU memory so it's immediately available when the GPU has\n",
    " finished processing the previous batch, so you can reach full GPU utilization.\n",
    "\n",
    "Keras features a range of utilities to help you turn raw data on disk into a `Dataset`:\n",
    "\n",
    "- `tf.keras.preprocessing.image_dataset_from_directory` turns image files sorted into\n",
    " class-specific folders into a labeled dataset of image tensors.\n",
    "- `tf.keras.preprocessing.text_dataset_from_directory` does the same for text files.\n",
    "\n",
    "In addition, the TensorFlow `tf.data` includes other similar utilities, such as\n",
    "`tf.data.experimental.make_csv_dataset` to load structured data from CSV files.\n",
    "\n",
    "**Example: obtaining a labeled dataset from image files on disk**\n",
    "\n",
    "Supposed you have image files sorted by class in different folders, like this:\n",
    "\n",
    "```\n",
    "main_directory/\n",
    "...class_a/\n",
    "......a_image_1.jpg\n",
    "......a_image_2.jpg\n",
    "...class_b/\n",
    "......b_image_1.jpg\n",
    "......b_image_2.jpg\n",
    "```\n",
    "\n",
    "Then you can do:\n",
    "\n",
    "```python\n",
    "# Create a dataset.\n",
    "dataset = keras.preprocessing.image_dataset_from_directory(\n",
    "  'path/to/main_directory', batch_size=64, image_size=(200, 200))\n",
    "\n",
    "# For demonstration, iterate over the batches yielded by the dataset.\n",
    "for data, labels in dataset:\n",
    "   print(data.shape)  # (64, 200, 200, 3)\n",
    "   print(data.dtype)  # float32\n",
    "   print(labels.shape)  # (64,)\n",
    "   print(labels.dtype)  # int32\n",
    "```\n",
    "\n",
    "The label of a sample is the rank of its folder in alphanumeric order. Naturally, this\n",
    " can also be configured explicitly by passing, e.g.\n",
    "`class_names=['class_a', 'class_b']`, in which cases label `0` will be `class_a` and\n",
    " `1` will be `class_b`.\n",
    "\n",
    "**Example: obtaining a labeled dataset from text files on disk**\n",
    "\n",
    "Likewise for text: if you have `.txt` documents sorted by class in different folders,\n",
    " you can do:\n",
    "\n",
    "```python\n",
    "dataset = keras.preprocessing.text_dataset_from_directory(\n",
    "  'path/to/main_directory', batch_size=64)\n",
    "\n",
    "# For demonstration, iterate over the batches yielded by the dataset.\n",
    "for data, labels in dataset:\n",
    "   print(data.shape)  # (64,)\n",
    "   print(data.dtype)  # string\n",
    "   print(labels.shape)  # (64,)\n",
    "   print(labels.dtype)  # int32\n",
    "```\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Data preprocessing with Keras\n",
    "\n",
    "Once your data is in the form of string/int/float NumpPy arrays, or a `Dataset` object\n",
    " (or Python generator) that yields batches of string/int/float tensors,\n",
    "it is time to **preprocess** the data. This can mean:\n",
    "\n",
    "- Tokenization of string data, followed by token indexing.\n",
    "- Feature normalization.\n",
    "- Rescaling the data to small values (in general, input values to a neural network\n",
    "should be close to zero -- typically we expect either data with zero-mean and\n",
    " unit-variance, or data in the `[0, 1]` range.\n",
    "\n",
    "### The ideal machine learning model is end-to-end\n",
    "\n",
    "In general, you should seek to do data preprocessing **as part of your model** as much\n",
    "as possible, not via an external data preprocessing pipeline. That's because external\n",
    "data preprocessing makes your models less portable when it's time to use them in\n",
    "production. Consider a model that processes text: it uses a specific tokenization\n",
    "algorithm and a specific vocabulary index. When you want to ship your model to a\n",
    "mobile app or a JavaScript app, you will need to recreate the exact same preprocessing\n",
    "setup in the target language. This can get very tricky: any small discrepancy between\n",
    "the original pipeline and the one you recreate has the potential to completely\n",
    " invalidate your model, or at least severely degrade its performance.\n",
    "\n",
    "It would be much easier to be able to simply export an end-to-end model that already\n",
    "includes preprocessing. **The ideal model should expect as input something as close as\n",
    "possible to raw data: an image model should expect RGB pixel values in the `[0, 255]`\n",
    "range, and a text model should accept strings of `utf-8` characters.** That way, the\n",
    " consumer of the exported model doesn't have\n",
    "to know about the preprocessing pipeline.\n",
    "\n",
    "### Using Keras preprocessing layers\n",
    "\n",
    "In Keras, you do in-model data preprocessing via **preprocessing layers**. This\n",
    " includes:\n",
    "\n",
    "- Vectorizing raw strings of text via the `TextVectorization` layer\n",
    "- Feature normalization via the `Normalization` layer\n",
    "- Image rescaling, cropping, or image data augmentation\n",
    "\n",
    "The key advatange of using Keras preprocessing layers is that **they can be included\n",
    " directly into your model**, either during training or after training,\n",
    "which makes your models portable.\n",
    "\n",
    "Some preprocessing layers have a state:\n",
    "\n",
    "- `TextVectorization` holds an index mapping words or tokens to integer indices\n",
    "- `Normalization` holds the mean and variance of your features\n",
    "\n",
    "The state of a preprocessing layers is obtained by calling `layer.adapt(data)` on a\n",
    " sample of the training data (or all of it).\n",
    "\n",
    "\n",
    "**Example: turning strings into sequences of integer word indices**\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "from tensorflow.keras.layers.experimental.preprocessing import TextVectorization\n",
    "\n",
    "# Example training data, of dtype `string`.\n",
    "training_data = np.array([[\"This is the 1st sample.\"], [\"And here's the 2nd sample.\"]])\n",
    "\n",
    "# Create a TextVectorization layer instance. It can be configured to either\n",
    "# return integer token indices, or a dense token representation (e.g. multi-hot\n",
    "# or TF-IDF). The text standardization and text splitting algorithms are fully\n",
    "# configurable.\n",
    "vectorizer = TextVectorization(output_mode=\"int\")\n",
    "\n",
    "# Calling `adapt` on an array or dataset makes the layer generate a vocabulary\n",
    "# index for the data, which can then be reused when seeing new data.\n",
    "vectorizer.adapt(training_data)\n",
    "\n",
    "# After calling adapt, the layer is able to encode any n-gram it has seen before\n",
    "# in the `adapt()` data. Unknown n-grams are encoded via an \"out-of-vocabulary\"\n",
    "# token.\n",
    "integer_data = vectorizer(training_data)\n",
    "print(integer_data)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "**Example: turning strings into sequences of one-hot encoded bigrams**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "from tensorflow.keras.layers.experimental.preprocessing import TextVectorization\n",
    "\n",
    "# Example training data, of dtype `string`.\n",
    "training_data = np.array([[\"This is the 1st sample.\"], [\"And here's the 2nd sample.\"]])\n",
    "\n",
    "# Create a TextVectorization layer instance. It can be configured to either\n",
    "# return integer token indices, or a dense token representation (e.g. multi-hot\n",
    "# or TF-IDF). The text standardization and text splitting algorithms are fully\n",
    "# configurable.\n",
    "vectorizer = TextVectorization(output_mode=\"binary\", ngrams=2)\n",
    "\n",
    "# Calling `adapt` on an array or dataset makes the layer generate a vocabulary\n",
    "# index for the data, which can then be reused when seeing new data.\n",
    "vectorizer.adapt(training_data)\n",
    "\n",
    "# After calling adapt, the layer is able to encode any n-gram it has seen before\n",
    "# in the `adapt()` data. Unknown n-grams are encoded via an \"out-of-vocabulary\"\n",
    "# token.\n",
    "integer_data = vectorizer(training_data)\n",
    "print(integer_data)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "**Example: normalizing features**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "from tensorflow.keras.layers.experimental.preprocessing import Normalization\n",
    "\n",
    "# Example image data, with values in the [0, 255] range\n",
    "training_data = np.random.randint(0, 256, size=(64, 200, 200, 3)).astype(\"float32\")\n",
    "\n",
    "normalizer = Normalization(axis=-1)\n",
    "normalizer.adapt(training_data)\n",
    "\n",
    "normalized_data = normalizer(training_data)\n",
    "print(\"var: %.4f\" % np.var(normalized_data))\n",
    "print(\"mean: %.4f\" % np.mean(normalized_data))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "**Example: rescaling & center-cropping images**\n",
    "\n",
    "Both the `Rescaling` layer and the `CenterCrop` layer are stateless, so it isn't\n",
    " necessary to call `adapt()` in this case.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "from tensorflow.keras.layers.experimental.preprocessing import CenterCrop\n",
    "from tensorflow.keras.layers.experimental.preprocessing import Rescaling\n",
    "\n",
    "# Example image data, with values in the [0, 255] range\n",
    "training_data = np.random.randint(0, 256, size=(64, 200, 200, 3)).astype(\"float32\")\n",
    "\n",
    "cropper = CenterCrop(height=150, width=150)\n",
    "scaler = Rescaling(scale=1.0 / 255)\n",
    "\n",
    "output_data = scaler(cropper(training_data))\n",
    "print(\"shape:\", output_data.shape)\n",
    "print(\"min:\", np.min(output_data))\n",
    "print(\"max:\", np.max(output_data))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Building models with the Keras Functional API\n",
    "\n",
    "A \"layer\" is a simple input-output transformation (such as the scaling &\n",
    "center-cropping transformations above). For instance, here's a linear projection layer\n",
    " that maps its inputs to a 16-dimensional feature space:\n",
    "\n",
    "```python\n",
    "dense = keras.layers.Dense(units=16)\n",
    "```\n",
    "\n",
    "A \"model\" is a directed acyclic graph of layers. You can think of a model as a\n",
    "\"bigger layer\" that encompasses multiple sublayers and that can be trained via exposure\n",
    " to data.\n",
    "\n",
    "The most common and most powerful way to build Keras models is the Functional API. To\n",
    "build models with the Functional API, you start by specifying the shape (and\n",
    "optionally the dtype) of your inputs. If any dimension of your input can vary, you can\n",
    "specify it as `None`. For instance, an input for 200x200 RGB image would have shape\n",
    "`(200, 200, 3)`, but an input for RGB images of any size would have shape `(None,\n",
    " None, 3)`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "# Let's say we expect our inputs to be RGB images of arbitrary size\n",
    "inputs = keras.Input(shape=(None, None, 3))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "After defining your input(s), you chain layer transformations on top of your inputs,\n",
    " until your final output:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "from tensorflow.keras import layers\n",
    "\n",
    "# Center-crop images to 150x150\n",
    "x = CenterCrop(height=150, width=150)(inputs)\n",
    "# Rescale images to [0, 1]\n",
    "x = Rescaling(scale=1.0 / 255)(x)\n",
    "\n",
    "# Apply some convolution and pooling layers\n",
    "x = layers.Conv2D(filters=32, kernel_size=(3, 3), activation=\"relu\")(x)\n",
    "x = layers.MaxPooling2D(pool_size=(3, 3))(x)\n",
    "x = layers.Conv2D(filters=32, kernel_size=(3, 3), activation=\"relu\")(x)\n",
    "x = layers.MaxPooling2D(pool_size=(3, 3))(x)\n",
    "x = layers.Conv2D(filters=32, kernel_size=(3, 3), activation=\"relu\")(x)\n",
    "\n",
    "# Apply global average pooling to get flat feature vectors\n",
    "x = layers.GlobalAveragePooling2D()(x)\n",
    "\n",
    "# Add a dense classifier on top\n",
    "num_classes = 10\n",
    "outputs = layers.Dense(num_classes, activation=\"softmax\")(x)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "Once you have defined the directed acyclic graph of layers that turns your input(s) into\n",
    " your outputs, instantiate a `Model` object:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "model = keras.Model(inputs=inputs, outputs=outputs)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "This model behaves basically like a bigger layer. You can call it on batches of data, like\n",
    " this:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "data = np.random.randint(0, 256, size=(64, 200, 200, 3)).astype(\"float32\")\n",
    "processed_data = model(data)\n",
    "print(processed_data.shape)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "You can print a summary of how your data gets transformed at each stage of the model.\n",
    " This is useful for debugging.\n",
    "\n",
    "Note that the output shape displayed for each layers includes the **batch size**. Here\n",
    " the batch size is None, which indicates our model can process batchs of any size.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "model.summary()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "The Functional API also makes it easy to build models that have multiple inputs (for\n",
    "instance, an image *and* its metadata) or multiple outputs (for instance, predicting\n",
    "the class of the image *and* the likelihood that a user will click on it). For a\n",
    " deeper dive into what you can do, see our\n",
    "[guide to the Functional API](/guides/functional_api/).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Training models with `fit()`\n",
    "\n",
    "At this point, you know:\n",
    "\n",
    "- How to prepare your data (e.g. as a NumPy array or a `tf.data.Dataset` object)\n",
    "- How to build a model that will process your data\n",
    "\n",
    "The next step is to train your model on your data. The `Model` class features a\n",
    "built-in training loop, the `fit()` method. It accepts `Dataset` objects, Python\n",
    " generators that yield batches of data, or NumPy arrays.\n",
    "\n",
    "Before you can call `fit()`, you need to specify an optimizer and a loss function (we\n",
    " assume you are already familiar with these concepts). This is the `compile()` step:\n",
    "\n",
    "```python\n",
    "model.compile(optimizer=keras.optimizers.RMSprop(learning_rate=1e-3),\n",
    "              loss=keras.losses.CategoricalCrossentropy())\n",
    "```\n",
    "\n",
    "Loss and optimizer can be specified via their string identifiers (in this case\n",
    "their default constructor argument values are used):\n",
    "\n",
    "\n",
    "```python\n",
    "model.compile(optimizer='rmsprop', loss='categorical_crossentropy')\n",
    "```\n",
    "\n",
    "Once your model is compiled, you can start \"fitting\" the model to the data.\n",
    "Here's what fitting a model looks like with NumPy data:\n",
    "\n",
    "```python\n",
    "model.fit(numpy_array_of_samples, numpy_array_of_labels,\n",
    "          batch_size=32, epochs=10)\n",
    "```\n",
    "\n",
    "Besides the data, you have to specify two key parameters: the `batch_size` and\n",
    "the number of epochs (iterations on the data). Here our data will get sliced on batches\n",
    " of 32 samples, and the model will iterate 10 times over the data during training.\n",
    "\n",
    "Here's what fitting a model looks like with a dataset:\n",
    "\n",
    "```python\n",
    "model.fit(dataset_of_samples_and_labels, epochs=10)\n",
    "```\n",
    "\n",
    "Since the data yielded by a dataset is expect to be already batched, you don't need to\n",
    " specify the batch size here.\n",
    "\n",
    "Let's look at it in practice with a toy example model that learns to classify MNIST\n",
    " digits:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "# Get the data as Numpy arrays\n",
    "(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n",
    "\n",
    "# Build a simple model\n",
    "inputs = keras.Input(shape=(28, 28))\n",
    "x = layers.experimental.preprocessing.Rescaling(1.0 / 255)(inputs)\n",
    "x = layers.Flatten()(x)\n",
    "x = layers.Dense(128, activation=\"relu\")(x)\n",
    "x = layers.Dense(128, activation=\"relu\")(x)\n",
    "outputs = layers.Dense(10, activation=\"softmax\")(x)\n",
    "model = keras.Model(inputs, outputs)\n",
    "model.summary()\n",
    "\n",
    "# Compile the model\n",
    "model.compile(optimizer=\"adam\", loss=\"sparse_categorical_crossentropy\")\n",
    "\n",
    "# Train the model for 1 epoch from Numpy data\n",
    "batch_size = 64\n",
    "print(\"Fit on NumPy data\")\n",
    "history = model.fit(x_train, y_train, batch_size=batch_size, epochs=1)\n",
    "\n",
    "# Train the model for 1 epoch using a dataset\n",
    "dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(batch_size)\n",
    "print(\"Fit on Dataset\")\n",
    "history = model.fit(dataset, epochs=1)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "The `fit()` call returns a \"history\" object which records what happened over the course\n",
    "of training. The `history.history` dict contains per-epoch timeseries of metrics\n",
    "values (here we have only one metric, the loss, and one epoch, so we only get a single\n",
    " scalar):\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "print(history.history)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "For a detailed overview of how to use `fit()`, see the\n",
    "[guide to training & evaluation with the built-in Keras methods](\n",
    "  /guides/training_with_built_in_methods/).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "### Keeping track of performance metrics\n",
    "\n",
    "As you're training a model, you want to keep of track of metrics such as classification\n",
    "accuracy, precision, recall, AUC, etc. Besides, you want to monitor these metrics not\n",
    " only on the training data, but also on a validation set.\n",
    "\n",
    "**Monitoring metrics**\n",
    "\n",
    "You can pass a list of metric objects to `compile()`, like this:\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "model.compile(\n",
    "    optimizer=\"adam\",\n",
    "    loss=\"sparse_categorical_crossentropy\",\n",
    "    metrics=[keras.metrics.SparseCategoricalAccuracy(name=\"acc\")],\n",
    ")\n",
    "history = model.fit(dataset, epochs=1)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "**Passing validation data to `fit()`**\n",
    "\n",
    "You can pass validation data to `fit()` to monitor your validation loss & validation\n",
    " metrics. Validation metrics get reported at the end of each epoch.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "val_dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(batch_size)\n",
    "history = model.fit(dataset, epochs=1, validation_data=val_dataset)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "### Using callbacks for checkpointing (and more)\n",
    "\n",
    "If training goes on for more than a few minutes, it's important to save your model at\n",
    " regular intervals during training. You can then use your saved models\n",
    "to restart training in case your training process crashes (this is important for\n",
    "multi-worker distributed training, since with many workers at least one of them is\n",
    " bound to fail at some point).\n",
    "\n",
    "An important feature of Keras is **callbacks**, configured in `fit()`. Callbacks are\n",
    " objects that get called by the model at different point during training, in particular:\n",
    "\n",
    "- At the beginning and end of each batch\n",
    "- At the beginning and end of each epoch\n",
    "\n",
    "Callbacks are a way to make model trainable entirely scriptable.\n",
    "\n",
    "You can use callbacks to periodically save your model. Here's a simple example: a\n",
    " `ModelCheckpoint` callback\n",
    "configured to save the model at the end of every epoch. The filename will include the\n",
    " current epoch.\n",
    "\n",
    "```python\n",
    "callbacks = [\n",
    "    keras.callbacks.ModelCheckpoint(\n",
    "        filepath='path/to/my/model_{epoch}',\n",
    "        save_freq='epoch')\n",
    "]\n",
    "model.fit(dataset, epochs=2, callbacks=callbacks)\n",
    "```\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "You can also use callbacks to do things like periodically changing the learning of your\n",
    "optimizer, streaming metrics to a Slack bot, sending yourself an email notification\n",
    " when training is complete, etc.\n",
    "\n",
    "For detailed overview of what callbacks are available and how to write your own, see\n",
    "the [callbacks API documentation](/api/callbacks/) and the\n",
    "[guide to writing custom callbacks](/guides/writing_your_own_callbacks/).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "### Monitoring training progress with TensorBoard\n",
    "\n",
    "Staring at the Keras progress bar isn't the most ergonomic way to monitor how your loss\n",
    " and metrics are evolving over time. There's a better solution:\n",
    "[TensorBoard](https://www.tensorflow.org/tensorboard),\n",
    "a web application that can display real-time graphs of your metrics (and more).\n",
    "\n",
    "To use TensorBoard with `fit()`, simply pass a `keras.callbacks.TensorBoard` callback\n",
    " specifying the directory where to store TensorBoard logs:\n",
    "\n",
    "\n",
    "```python\n",
    "callbacks = [\n",
    "    keras.callbacks.TensorBoard(log_dir='./logs')\n",
    "]\n",
    "model.fit(dataset, epochs=2, callbacks=callbacks)\n",
    "```\n",
    "\n",
    "You can then launch a TensorBoard instance that you can open in your browser to monitor\n",
    " the logs getting written to this location:\n",
    "\n",
    "```\n",
    "tensorboard --logdir=./logs\n",
    "```\n",
    "\n",
    "What's more, you can launch an in-line TensorBoard tab when training models in Jupyter\n",
    " / Colab notebooks.\n",
    "[Here's more information](https://www.tensorflow.org/tensorboard/tensorboard_in_notebooks).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "### After `fit()`: evaluating test performance & generating predictions on new data\n",
    "\n",
    "Once you have a trained model, you can evaluate its loss and metrics on new data via\n",
    " `evaluate()`:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "loss, acc = model.evaluate(val_dataset)  # returns loss and metrics\n",
    "print(\"loss: %.2f\" % loss)\n",
    "print(\"acc: %.2f\" % acc)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "You can also generate NumPy arrays of predictions (the activations of the output\n",
    " layer(s) in the model) via `predict()`:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "predictions = model.predict(val_dataset)\n",
    "print(predictions.shape)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Using `fit()` with a custom training step\n",
    "\n",
    "By default, `fit()` is configured for **supervised learning**. If you need a different\n",
    " kind of training loop (for instance, a GAN training loop), you\n",
    "can provide your own implementation of the `Model.train_step()` method. This is the\n",
    " method that is repeatedly called during `fit()`.\n",
    "\n",
    "Metrics, callbacks, etc. will work as usual.\n",
    "\n",
    "Here's a simple example that reimplements what `fit()` normally does:\n",
    "\n",
    "```python\n",
    "class CustomModel(keras.Model):\n",
    "  def train_step(self, data):\n",
    "    # Unpack the data. Its structure depends on your model and\n",
    "    # on what you pass to `fit()`.\n",
    "    x, y = data\n",
    "    with tf.GradientTape() as tape:\n",
    "      y_pred = self(x, training=True)  # Forward pass\n",
    "      # Compute the loss value\n",
    "      # (the loss function is configured in `compile()`)\n",
    "      loss = self.compiled_loss(y, y_pred,\n",
    "                                regularization_losses=self.losses)\n",
    "    # Compute gradients\n",
    "    trainable_vars = self.trainable_variables\n",
    "    gradients = tape.gradient(loss, trainable_vars)\n",
    "    # Update weights\n",
    "    self.optimizer.apply_gradients(zip(gradients, trainable_vars))\n",
    "    # Update metrics (includes the metric that tracks the loss)\n",
    "    self.compiled_metrics.update_state(y, y_pred)\n",
    "    # Return a dict mapping metric names to current value\n",
    "    return {m.name: m.result() for m in self.metrics}\n",
    "\n",
    "# Construct and compile an instance of CustomModel\n",
    "inputs = keras.Input(shape=(32,))\n",
    "outputs = keras.layers.Dense(1)(inputs)\n",
    "model = CustomModel(inputs, outputs)\n",
    "model.compile(optimizer='adam', loss='mse', metrics=[...])\n",
    "\n",
    "# Just use `fit` as usual\n",
    "model.fit(dataset, epochs=3, callbacks=...)\n",
    "```\n",
    "\n",
    "For a detailed overview of how you customize the built-in training & evaluation loops,\n",
    " see the guide:\n",
    "[\"Customizing what happens in `fit()`\"](/guides/customizing_what_happens_in_fit/).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Debugging your model with eager execution\n",
    "\n",
    "If you write custom training steps or custom layers, you will need to debug them. The\n",
    "debugging experience is an integral part of a framework: with Keras, the debugging\n",
    " workflow is designed with the user in mind.\n",
    "\n",
    "By default, your Keras models are compiled to highly-optimized computation graphs that\n",
    "deliver fast execution times. That means that the Python code you write (e.g. in a\n",
    "custom `train_step`) is not the code you are actually executing. This introduces a\n",
    " layer of indirection that can make debugging hard.\n",
    "\n",
    "Debugging is best done step by step. You want to be able to sprinkle your code with\n",
    "`print()` statement to see what your data looks like after every operation, you want\n",
    "to be able to use `pdb`. You can achieve this by **running your model eagerly**. With\n",
    " eager execution, the Python code you write is the code that gets executed.\n",
    "\n",
    "Simply pass `run_eagerly=True` to `compile()`:\n",
    "\n",
    "```python\n",
    "model.compile(optimizer='adam', loss='mse', run_eagerly=True)\n",
    "```\n",
    "\n",
    "Of course, the downside is that it makes your model significantly slower. Make sure to\n",
    "switch it back off to get the benefits of compiled computation graphs once you are\n",
    " done debugging!\n",
    "\n",
    "In general, you will use `run_eagerly=True` every time you need to debug what's\n",
    " happening inside your `fit()` call.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Speeding up training with multiple GPUs\n",
    "\n",
    "Keras has built-in industry-strength support for multi-GPU training and distributed\n",
    " multi-worker training, via the `tf.distribute` API.\n",
    "\n",
    "If you have multiple GPUs on your machine, you can train your model on all of them by:\n",
    "\n",
    "- Creating a `tf.distribute.MirroredStrategy` object\n",
    "- Building & compiling your model inside the strategy's scope\n",
    "- Calling `fit()` and `evaluate()` on a dataset as usual\n",
    "\n",
    "```python\n",
    "# Create a MirroredStrategy.\n",
    "strategy = tf.distribute.MirroredStrategy()\n",
    "\n",
    "# Open a strategy scope.\n",
    "with strategy.scope():\n",
    "  # Everything that creates variables should be under the strategy scope.\n",
    "  # In general this is only model construction & `compile()`.\n",
    "  model = Model(...)\n",
    "  model.compile(...)\n",
    "\n",
    "# Train the model on all available devices.\n",
    "train_dataset, val_dataset, test_dataset = get_dataset()\n",
    "model.fit(train_dataset, epochs=2, validation_data=val_dataset)\n",
    "\n",
    "# Test the model on all available devices.\n",
    "model.evaluate(test_dataset)\n",
    "```\n",
    "\n",
    "For a detailed introduction to multi-GPU & distributed training, see\n",
    "[this guide](/guides/distributed_training/).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Doing preprocessing synchronously on-device vs. asynchronously on host CPU\n",
    "\n",
    "You've learned about preprocessing, and you've seen example where we put image\n",
    " preprocessing layers (`CenterCrop` and `Rescaling`) directly inside our model.\n",
    "\n",
    "Having preprocessing happen as part of the model during training\n",
    "is great if you want to do on-device preprocessing, for instance, GPU-accelerated\n",
    "feature normalization or image augmentation. But there are kinds of preprocessing that\n",
    "are not suited to this setup: in particular, text preprocessing with the\n",
    "`TextVectorization` layer. Due to its sequential nature and due to the fact that it\n",
    " can only run on CPU, it's often a good idea to do **asynchronous preprocessing**.\n",
    "\n",
    "With asynchronous preprocessing, your preprocessing operations will run on CPU, and the\n",
    "preprocessed samples will be buffered into a queue while your GPU is busy with\n",
    "previous batch of data. The next batch of preprocessed samples will then be fetched\n",
    "from the queue to the GPU memory right before the GPU becomes available again\n",
    "(prefetching). This ensures that preprocessing will not be blocking and that your GPU\n",
    " can run at full utilization.\n",
    "\n",
    "To do asynchronous preprocessing, simply use `dataset.map` to inject a preprocessing\n",
    " operation into your data pipeline:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "# Example training data, of dtype `string`.\n",
    "samples = np.array([[\"This is the 1st sample.\"], [\"And here's the 2nd sample.\"]])\n",
    "labels = [[0], [1]]\n",
    "\n",
    "# Prepare a TextVectorization layer.\n",
    "vectorizer = TextVectorization(output_mode=\"int\")\n",
    "vectorizer.adapt(samples)\n",
    "\n",
    "# Asynchronous preprocessing: the text vectorization is part of the tf.data pipeline.\n",
    "# First, create a dataset\n",
    "dataset = tf.data.Dataset.from_tensor_slices((samples, labels)).batch(2)\n",
    "# Apply text vectorization to the samples\n",
    "dataset = dataset.map(lambda x, y: (vectorizer(x), y))\n",
    "# Prefetch with a buffer size of 2 batches\n",
    "dataset = dataset.prefetch(2)\n",
    "\n",
    "# Our model should expect sequences of integers as inputs\n",
    "inputs = keras.Input(shape=(None,), dtype=\"int64\")\n",
    "x = layers.Embedding(input_dim=10, output_dim=32)(inputs)\n",
    "outputs = layers.Dense(1)(x)\n",
    "model = keras.Model(inputs, outputs)\n",
    "\n",
    "model.compile(optimizer=\"adam\", loss=\"mse\", run_eagerly=True)\n",
    "model.fit(dataset)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "Compare this to doing text vectorization as part of the model:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "# Our dataset will yield samples that are strings\n",
    "dataset = tf.data.Dataset.from_tensor_slices((samples, labels)).batch(2)\n",
    "\n",
    "# Our model should expect strings as inputs\n",
    "inputs = keras.Input(shape=(1,), dtype=\"string\")\n",
    "x = vectorizer(inputs)\n",
    "x = layers.Embedding(input_dim=10, output_dim=32)(x)\n",
    "outputs = layers.Dense(1)(x)\n",
    "model = keras.Model(inputs, outputs)\n",
    "\n",
    "model.compile(optimizer=\"adam\", loss=\"mse\", run_eagerly=True)\n",
    "model.fit(dataset)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "When training text models on CPU, you will generally not see any performance difference\n",
    "between the two setups. When training on GPU, however, doing asynchronous buffered\n",
    "preprocessing on the host CPU while the GPU is running the model itself can result in\n",
    " a significant speedup.\n",
    "\n",
    "After training, if you to export an end-to-end model that includes the preprocessing\n",
    " layer(s), this is easy to do, since `TextVectorization` is a layer:\n",
    "\n",
    "```python\n",
    "inputs = keras.Input(shape=(1,), dtype='string')\n",
    "x = vectorizer(inputs)\n",
    "outputs = trained_model(x)\n",
    "end_to_end_model = keras.Model(inputs, outputs)\n",
    "```\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Finding the best model configuration with hyperparameter tuning\n",
    "\n",
    "Once you have a working model, you're going to want to optimize its configuration --\n",
    "architecture choices, layer sizes, etc. Human intuition can only go so far, so you'll\n",
    " want to leverage a systematic approach: hyperparameter search.\n",
    "\n",
    "You can use\n",
    "[Keras Tuner](https://keras-team.github.io/keras-tuner/documentation/tuners/) to find\n",
    " the best hyperparameter for your Keras models. It's as easy as calling `fit()`.\n",
    "\n",
    "Here how it works.\n",
    "\n",
    "First, place your model definition in a function, that takes a single `hp` argument.\n",
    "Inside this function, replace any value you want to tune with a call to hyperparameter\n",
    " sampling methods, e.g. `hp.Int()` or `hp.Choice()`:\n",
    "\n",
    "```python\n",
    "def build_model(hp):\n",
    "    inputs = keras.Input(shape=(784,))\n",
    "    x = layers.Dense(\n",
    "        units=hp.Int('units', min_value=32, max_value=512, step=32),\n",
    "        activation='relu'))(inputs)\n",
    "    outputs = layers.Dense(10, activation='softmax')(x)\n",
    "    model = keras.Model(inputs, outputs)\n",
    "    model.compile(\n",
    "        optimizer=keras.optimizers.Adam(\n",
    "            hp.Choice('learning_rate',\n",
    "                      values=[1e-2, 1e-3, 1e-4])),\n",
    "        loss='sparse_categorical_crossentropy',\n",
    "        metrics=['accuracy'])\n",
    "    return model\n",
    "```\n",
    "\n",
    "The function should return a compiled model.\n",
    "\n",
    "Next, instantiate a tuner object specifying your optimiation objective and other search\n",
    " parameters:\n",
    "\n",
    "\n",
    "```python\n",
    "import kerastuner\n",
    "\n",
    "tuner = kerastuner.tuners.Hyperband(\n",
    "  build_model,\n",
    "  objective='val_loss',\n",
    "  max_epochs=100,\n",
    "  max_trials=200,\n",
    "  executions_per_trial=2,\n",
    "  directory='my_dir')\n",
    "```\n",
    "\n",
    "Finally, start the search with the `search()` method, which takes the same arguments as\n",
    " `Model.fit()`:\n",
    "\n",
    "```python\n",
    "tuner.search(dataset, validation_data=val_dataset)\n",
    "```\n",
    "\n",
    "When search is over, you can retrieve the best model(s):\n",
    "\n",
    "```python\n",
    "models = tuner.get_best_models(num_models=2)\n",
    "```\n",
    "\n",
    "Or print a summary of the results:\n",
    "\n",
    "```python\n",
    "tuner.results_summary()\n",
    "```\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## End-to-end examples\n",
    "\n",
    "To familiarize yourself with the concepts in this introduction, see the following\n",
    " end-to-end examples:\n",
    "\n",
    "- [Text classification](/examples/nlp/text_classification_from_scratch/)\n",
    "- [Image classification](/examples/vision/image_classification_from_scratch/)\n",
    "- [Credit card fraud detection](/examples/structured_data/imbalanced_classification/)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## What to learn next\n",
    "\n",
    "- Learn more about the\n",
    "[Functional API](/guides/functional_api/).\n",
    "- Learn more about the\n",
    "[features of `fit()` and `evaluate()`](/guides/training_with_built_in_methods/).\n",
    "- Learn more about\n",
    "[callbacks](/guides/writing_your_own_callbacks/).\n",
    "- Learn more about\n",
    "[creating your own custom training steps](/guides/customizing_what_happens_in_fit/).\n",
    "- Learn more about\n",
    "[multi-GPU and distributed training](/guides/distributed_training/).\n",
    "- Learn how to do [transfer learning](/guides/transfer_learning/).\n"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "intro_to_keras_for_engineers",
   "private_outputs": false,
   "provenance": [],
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}